package com.zx.config;/**
 * Author:JasonZ
 * Data:2023/4/18
 */

import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: ecommerce-parent
 *
 * @description: 定义路由的增删改业务
 *
 * @author: JasonZ
 *
 * @create: 2023-04-18 10:08
 **/
@Component
@Slf4j
public class DynamicRoutesService implements ApplicationEventPublisherAware {

    //应用事件发布者
    private ApplicationEventPublisher publisher;;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher=applicationEventPublisher;
    }

    //写入路由定义
    @Resource
    private RouteDefinitionWriter routeDefinitionWriter;

    //查找路由定义
    @Resource
    private RouteDefinitionLocator routeDefinitionLocator;

    /**
     * 添加路由定义
     * @param routeDefinition
     * @return
     */
    // WebFlux: 非阻塞IO  发布订阅机制
    // Mono----> Object
    // Flux----> List
    // List[番茄炒蛋，青椒肉丝]  Flux[番茄炒蛋，青椒肉丝]

    public String addRouteDefinition(RouteDefinition routeDefinition){
        log.info("gateway add route[{}]",routeDefinition);
        /*subscribe 订阅*/
        routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
        // 发布路由更新事件
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
        return "success";
    }

    private String deleteById(String id){
        log.info("gateway delete route :[{}]",id);
        this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
        return "success";
    }


    public String updateList(List<RouteDefinition> definitions){
        log.info("gateway update routes: [{}]",definitions);
        // 删除现有的所有路由定义

        List<RouteDefinition> routeDefinitions =
                routeDefinitionLocator.getRouteDefinitions().buffer().blockFirst();
        if(!Collections.isEmpty(routeDefinitions)){
            routeDefinitions.forEach(r->deleteById(r.getId()));
        }
        // 在添加新的路由定义
        definitions.forEach(d->addRouteDefinition(d));
        return "success";
    }


}
